package com.x.wx.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.weixin.iot.msg.InEquDataMsg;
import com.jfinal.weixin.iot.msg.InEqubindEvent;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.MediaApi;
import com.jfinal.weixin.sdk.api.UserApi;
import com.jfinal.weixin.sdk.jfinal.MsgController;
import com.jfinal.weixin.sdk.jfinal.MsgInterceptor;
import com.jfinal.weixin.sdk.msg.in.*;
import com.jfinal.weixin.sdk.msg.in.card.*;
import com.jfinal.weixin.sdk.msg.in.event.*;
import com.jfinal.weixin.sdk.msg.in.speech_recognition.InSpeechRecognitionResults;
import com.jfinal.weixin.sdk.msg.out.OutImageMsg;
import com.jfinal.weixin.sdk.msg.out.OutNewsMsg;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;
import com.jfinal.weixin.sdk.msg.out.OutVideoMsg;
import com.vdurmont.emoji.EmojiParser;
import com.x.wx.model.WxKeyword;
import com.x.wx.model.WxUser;
import com.x.wx.rpc.WxKeywordRpcService;
import com.x.wx.rpc.WxUserRpcService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.util.Date;
import java.util.List;

/**
 * 微信消息控制器
 */
public class WxMsgController extends MsgController {

	private static final Logger logger = LoggerFactory.getLogger(WxMsgController.class);

	private WxUserRpcService wxUserRpcService = SpringUtils.getBean(WxUserRpcService.class);

	private WxKeywordRpcService wxKeywordRpcService = SpringUtils.getBean(WxKeywordRpcService.class);

	private final String defaultMsg = "欢迎关注！";

	/**
	 * 处理文字消息
	 */
	@Override
	protected void processInTextMsg(InTextMsg inTextMsg) {
		String content = inTextMsg.getContent().trim();
		sendKeywordMsg(getKeyword(this.getPara("accountId"), content), inTextMsg);
	}

	/**
	 * 处理图片消息
	 */
	@Override
	protected void processInImageMsg(InImageMsg inImageMsg) {
		OutImageMsg outImageMsg = new OutImageMsg(inImageMsg);
		outImageMsg.setMediaId(inImageMsg.getMediaId());
		render(outImageMsg);
	}

	/**
	 * 处理音频消息
	 */
	@Override
	protected void processInVoiceMsg(InVoiceMsg inVoiceMsg) {
	}

	@Before({MsgInterceptor.class})
	@Override
	public void index() {
//		logger.info(this.getPara("token"));
		//输出微信服务发送过来的xml消息
//		logger.info("接收消息：" + this.getInMsgXml());
		//获取并转换xml格式的消息
		InMsg inMsg = getInMsg();
		//解析消息并根据消息类型分发到相应的处理方法
		if (inMsg instanceof InTextMsg) {

			processInTextMsg((InTextMsg) inMsg);
		} else if (inMsg instanceof InImageMsg) {
			processInImageMsg((InImageMsg) inMsg);
		} else if (inMsg instanceof InVoiceMsg) {
			processInVoiceMsg((InVoiceMsg) inMsg);
		} else if (inMsg instanceof InVideoMsg) {
			processInVideoMsg((InVideoMsg) inMsg);
		} else if (inMsg instanceof InLocationMsg) {
			processInLocationMsg((InLocationMsg) inMsg);
		} else if (inMsg instanceof InLinkMsg) {
			processInLinkMsg((InLinkMsg) inMsg);
		} else if (inMsg instanceof InFollowEvent) {
			processInFollowEvent((InFollowEvent) inMsg);
		} else if (inMsg instanceof InQrCodeEvent) {
			processInQrCodeEvent((InQrCodeEvent) inMsg);
		} else if (inMsg instanceof InLocationEvent) {
			processInLocationEvent((InLocationEvent) inMsg);
		} else if (inMsg instanceof InMenuEvent) {
			processInMenuEvent((InMenuEvent) inMsg);
		} else if (inMsg instanceof InSpeechRecognitionResults) {
			processInSpeechRecognitionResults((InSpeechRecognitionResults) inMsg);
		} else {
			OutTextMsg outTextMsg = new OutTextMsg(inMsg);
			outTextMsg.setContent("success");
			render(outTextMsg);
		}
	}

	/**
	 * 处理视频消息
	 */
	@Override
	protected void processInVideoMsg(InVideoMsg inVideoMsg) {
	}

	/**
	 * 处理短视频消息
	 */
	@Override
	protected void processInShortVideoMsg(InShortVideoMsg inShortVideoMsg) {
	}

	/**
	 * 处理地理位置消息
	 */
	@Override
	protected void processInLocationMsg(InLocationMsg inLocationMsg) {
	}

	/**
	 * 处理链接消息
	 */
	@Override
	protected void processInLinkMsg(InLinkMsg inLinkMsg) {
	}

	/**
	 * 客服消息
	 */
	@Override
	protected void processInCustomEvent(InCustomEvent inCustomEvent) {
	}

	/**
	 * 关注/取消关注事件
	 */
	@Override
	protected void processInFollowEvent(InFollowEvent inFollowEvent) {
		String openId = inFollowEvent.getFromUserName();
		logger.info("微信用户open_id：" + openId);
		if (InFollowEvent.EVENT_INFOLLOW_SUBSCRIBE.equals(inFollowEvent.getEvent())) {//关注
			ApiResult res = UserApi.getUserInfo(openId);
			String nickname = res.getStr("nickname");
			String city = res.getStr("city");
			String province = res.getStr("province");
			String headimgurl = res.getStr("headimgurl");
			String accountId = this.getPara("accountId");
			int sex = res.getInt("sex");
			Date cDate = new Date();
			if(StringUtils.isNotEmpty(nickname)){
				nickname = EmojiParser.removeAllEmojis(nickname);
			}
			WxUser wxUser = new WxUser(openId, nickname, headimgurl, sex, province, city, 1, cDate, cDate, accountId);
			wxUserRpcService.insertWxUser(wxUser);
			sendKeywordMsg(getKeyword(this.getPara("accountId"), "welcome"), inFollowEvent);
		} else {//取消关注
			OutTextMsg outTextMsg = new OutTextMsg(inFollowEvent);
			outTextMsg.setContent("有人取消了关注");//取消关注后
			WxUser wxUser = new WxUser();
			WxUser whereWxUser = new WxUser();
			wxUser.setUserStatus(2);
			wxUser.setUserUpdateTime(new Date());
			whereWxUser.setUserOpenId(openId);
			wxUserRpcService.updateWxUser(wxUser, whereWxUser);
			render(outTextMsg);
		}
	}

	/**
	 * 二维码事件
	 */
	@Override
	protected void processInQrCodeEvent(InQrCodeEvent inQrCodeEvent) {
	}

	/**
	 * 地理位置事件
	 */
	@Override
	protected void processInLocationEvent(InLocationEvent inLocationEvent) {
	}

	/**
	 * 群发事件
	 */
	@Override
	protected void processInMassEvent(InMassEvent inMassEvent) {
	}

	/**
	 * 菜单事件
	 */
	@Override
	protected void processInMenuEvent(InMenuEvent inMenuEvent) {
		String content = inMenuEvent.getEventKey();
		if (inMenuEvent.getEvent().equalsIgnoreCase("click")) {
			sendKeywordMsg(getKeyword(this.getPara("accountId"), content), inMenuEvent);
		} else {
			OutTextMsg outTextMsg = new OutTextMsg(inMenuEvent);
			outTextMsg.setContent(defaultMsg);
			render(outTextMsg);
		}
	}

	@Override
	protected void processInSpeechRecognitionResults(InSpeechRecognitionResults inSpeechRecognitionResults) {
	}

	@Override
	protected void processInTemplateMsgEvent(InTemplateMsgEvent inTemplateMsgEvent) {
	}

	@Override
	protected void processInShakearoundUserShakeEvent(InShakearoundUserShakeEvent inShakearoundUserShakeEvent) {
	}

	@Override
	protected void processInVerifySuccessEvent(InVerifySuccessEvent inVerifySuccessEvent) {
	}

	@Override
	protected void processInVerifyFailEvent(InVerifyFailEvent inVerifyFailEvent) {
	}

	@Override
	protected void processInPoiCheckNotifyEvent(InPoiCheckNotifyEvent inPoiCheckNotifyEvent) {
	}

	@Override
	protected void processInWifiEvent(InWifiEvent inWifiEvent) {
	}

	@Override
	protected void processInUpdateMemberCardEvent(InUpdateMemberCardEvent inUpdateMemberCardEvent) {
	}

	@Override
	protected void processInUserPayFromCardEvent(InUserPayFromCardEvent inUserPayFromCardEvent) {
	}

	@Override
	protected void processInMerChantOrderEvent(InMerChantOrderEvent inMerChantOrderEvent) {
	}

	@Override
	protected void processIsNotDefinedEvent(InNotDefinedEvent inNotDefinedEvent) {
	}

	@Override
	protected void processIsNotDefinedMsg(InNotDefinedMsg inNotDefinedMsg) {
	}

	@Override
	protected void processInUserCardEvent(InUserCardEvent inUserCardEvent) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInUserGiftingCardEvent(InUserGiftingCardEvent msg) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInUserGetCardEvent(InUserGetCardEvent msg) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInUserConsumeCardEvent(InUserConsumeCardEvent msg) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInCardSkuRemindEvent(InCardSkuRemindEvent msg) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInCardPayOrderEvent(InCardPayOrderEvent msg) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInCardPassCheckEvent(InCardPassCheckEvent msg) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInEqubindEvent(InEqubindEvent msg) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInEquDataMsg(InEquDataMsg msg) {
		// TODO Auto-generated method stub

	}

	private WxKeyword getKeyword(String accountId, String content){
		WxKeyword wxKeyword = new WxKeyword();
		wxKeyword.setKeywordName(content);
		wxKeyword.setAccountId(accountId);
		List<WxKeyword> wxKeywords = wxKeywordRpcService.selectWxKeywordList(wxKeyword);
		if(wxKeywords != null && !wxKeywords.isEmpty()){
			return wxKeywords.get(0);
		}
		return null;
	}

	private void sendKeywordMsg(WxKeyword wxKeyword, InMsg inMsg){
		if (wxKeyword != null) {
			if (wxKeyword.getKeywordType().equals("text")) {
				OutTextMsg outTextMsg = new OutTextMsg(inMsg);
				outTextMsg.setContent(wxKeyword.getKeywordValue());
				render(outTextMsg);
			} else if (wxKeyword.getKeywordType().equals("image")) {
				OutImageMsg outImageMsg = new OutImageMsg(inMsg);
				outImageMsg.setMediaId(wxKeyword.getKeywordValue());
				render(outImageMsg);
			} else if (wxKeyword.getKeywordType().equals("voice")) {
				OutVideoMsg outVideoMsg = new OutVideoMsg(inMsg);
				outVideoMsg.setMediaId(wxKeyword.getKeywordValue());
				render(outVideoMsg);
			} else if (wxKeyword.getKeywordType().equals("news")) {
				OutNewsMsg outNewsMsg = new OutNewsMsg(inMsg);
				ApiResult res = MediaApi.getNews(wxKeyword.getKeywordValue());
				if (res.isSucceed()) {
					JSONObject obj = JSONObject.parseObject(res.getJson());
					JSONObject item = obj.getJSONArray("news_item").getJSONObject(0);
					outNewsMsg.addNews(item.getString("title"), item.getString("digest"), item.getString("thumb_url"), item.getString("url"));
					render(outNewsMsg);
				}
			}
		} else {
			OutTextMsg outTextMsg = new OutTextMsg(inMsg);
			outTextMsg.setContent(defaultMsg);
			render(outTextMsg);
		}
	}
}
